package com.ltu.payment.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import net.sf.json.JSONObject;

/**
 *  功能：<br>
 *  1.原生http请求
 *  
 *  @author w
 *  
 *  
 */
public class HttpUtil {
	/**
	 * 功能：<br>
	 * 1.发起GET请求<br>
	 * 2.发起POST请求<br>
	 * @param url 请求链接
	 * @param method GET|POST
	 * @param params map的请求参数，GET请求请传null
	 * @return
	 */
	public static String httpRequest(String url,String method,Map<String,Object> params){  
        StringBuffer buffer=null;  
        try{  
        URL httpUrl=new URL(url);  
        HttpURLConnection conn=(HttpURLConnection)httpUrl.openConnection();  
        conn.setRequestProperty("Content-type", "application/json"); 
        conn.setDoOutput(true);  
        conn.setDoInput(true);  
        conn.setRequestMethod(method);  
        conn.connect();  
        if(null!=params){  
            JSONObject obj=JSONObject.fromObject(params);
            OutputStream os=conn.getOutputStream();  
            String string=obj.toString();
            os.write(string.getBytes("utf-8"));  
            os.close();  
        }  
        InputStream is=conn.getInputStream();  
        InputStreamReader isr=new InputStreamReader(is,"utf-8");  
        BufferedReader br=new BufferedReader(isr);  
        buffer=new StringBuffer();  
        String line=null;  
        while((line=br.readLine())!=null){  
            buffer.append(line);  
        }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
        return buffer.toString();  
    }
}